package service

import (
    "errors"
    "strings"

    "github.com/go-admin-team/go-admin-core/sdk/service"
    "gorm.io/gorm"

    "go-admin/app/hunter/models"
    "go-admin/app/hunter/service/dto"
    "go-admin/common/actions"
    cDto "go-admin/common/dto"
)

type HtTalent struct {
    service.Service
}

// GetPage 获取HtTalent列表
func (e *HtTalent) GetPage(c *dto.HtTalentGetPageReq, p *actions.DataPermission, list *[]models.HtTalent, count *int64) error {
    var err error
    var data models.HtTalent
    byProjectId := false
    if c.ProjectId > 0 {
        byProjectId = true
    }

    orFunc := func(db *gorm.DB) *gorm.DB {
        return db
    }
    if strings.TrimSpace(c.NameOrPhone) != "" {
        orFunc = func(db *gorm.DB) *gorm.DB {
            db.Or("name like ?", "%"+c.NameOrPhone+"%")
            db.Or("phone like ?", "%"+c.NameOrPhone+"%")
            return db
        }
    }

    if byProjectId {
        var project models.HtProject
        project.Id = c.ProjectId
        err = e.Orm.Preload("Talents", func(db *gorm.DB) *gorm.DB {
            return db.Scopes(cDto.MakeCondition(c.GetNeedSearch()), cDto.Paginate(c.GetPageSize(), c.GetPageIndex()), actions.Permission(data.TableName(), p), orFunc)
        }).First(&project).Limit(-1).Offset(-1).Error
        *list = append(*list, project.Talents...)
    } else {
        err = e.Orm.Model(&data).
            Scopes(
                cDto.MakeCondition(c.GetNeedSearch()),
                cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
                actions.Permission(data.TableName(), p),
                orFunc,
            ).Find(list).Limit(-1).Offset(-1).
            Count(count).Error
    }

    if err != nil {
        e.Log.Errorf("HtTalentService GetPage error:%s \r\n", err)
        return err
    }
    return nil
}

// GetPageWithoutProjectId GetPage 获取HtTalent列表
func (e *HtTalent) GetPageWithoutProjectId(c *dto.HtTalentGetPageReq, p *actions.DataPermission, list *[]models.HtTalent, count *int64) error {
    var err error
    var data []models.HtTalent
    var md models.HtTalent
    orFunc := func(db *gorm.DB) *gorm.DB {
        return db
    }
    if strings.TrimSpace(c.NameOrPhone) == "" {
        return errors.New("请输入姓名或者电话")
    }

    err = e.Orm.Model(&md).Scopes(
        cDto.MakeCondition(c.GetNeedSearch()), cDto.Paginate(c.GetPageSize(), c.GetPageIndex()), actions.Permission(md.TableName(), p), orFunc, func(db *gorm.DB) *gorm.DB {
            // 过滤掉已经绑定了这个project的人
            return db.
                Joins("LEFT JOIN ht_project_talent pt ON pt.talent_id = ht_talent.id").
                Where("(ht_talent.name like ? or ht_talent.phone like ? ) and (pt.project_id IS NULL OR pt.project_id != ?)", "%"+c.NameOrPhone+"%", "%"+c.NameOrPhone+"%", c.ProjectId)
        }).Find(&data).Error
    *list = append(*list, data...)

    if err != nil {
        e.Log.Errorf("HtTalentService GetPage error:%s \r\n", err)
        return err
    }
    return nil
}

// Get 获取HtTalent对象
func (e *HtTalent) Get(d *dto.HtTalentGetReq, p *actions.DataPermission, model *models.HtTalent) error {
    var data models.HtTalent

    err := e.Orm.Model(&data).
        Scopes(
            actions.Permission(data.TableName(), p),
        ).Preload("ResumeList").
        First(model, d.GetId()).Error
    if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
        err = errors.New("查看对象不存在或无权查看")
        e.Log.Errorf("Service GetHtTalent error:%s \r\n", err)
        return err
    }
    if err != nil {
        e.Log.Errorf("db error:%s", err)
        return err
    }
    return nil
}

// Insert 创建HtTalent对象
func (e *HtTalent) Insert(c *dto.HtTalentInsertReq) error {
    var err error
    var data models.HtTalent
    c.Generate(&data)
    err = e.Orm.Create(&data).Error
    if err != nil {
        e.Log.Errorf("HtTalentService Insert error:%s \r\n", err)
        return err
    }
    return nil
}

// Update 修改HtTalent对象
func (e *HtTalent) Update(c *dto.HtTalentUpdateReq, p *actions.DataPermission) error {
    var err error
    var data = models.HtTalent{}
    e.Orm.Scopes(
        actions.Permission(data.TableName(), p),
    ).First(&data, c.GetId())
    c.Generate(&data)

    db := e.Orm.Save(&data)
    if err = db.Error; err != nil {
        e.Log.Errorf("HtTalentService Save error:%s \r\n", err)
        return err
    }
    if db.RowsAffected == 0 {
        return errors.New("无权更新该数据")
    }
    return nil
}

func (e *HtTalent) BatchInsert(talents []models.HtTalent, p *actions.DataPermission) error {
    var err error
    var data = models.HtTalent{}
    db := e.Orm.Scopes(
        actions.Permission(data.TableName(), p),
    ).Save(&talents)
    if err = db.Error; err != nil {
        e.Log.Errorf("BatchInsert Save error:%s \r\n", err)
        return err
    }
    if db.RowsAffected == 0 {
        return errors.New("无权更新该数据")
    }
    return nil
}
func (e *HtTalent) BatchBindInsert(projectTalents []models.HtProjectTalent, p *actions.DataPermission) error {
    var err error
    var data = models.HtTalent{}
    db := e.Orm.Scopes(
        actions.Permission(data.TableName(), p),
    ).Save(&projectTalents)
    if err = db.Error; err != nil {
        e.Log.Errorf("BatchBindInsert Save error:%s \r\n", err)
        return err
    }
    if db.RowsAffected == 0 {
        return errors.New("无权更新该数据")
    }
    return nil
}

// Remove 删除HtTalent
func (e *HtTalent) Remove(d *dto.HtTalentDeleteReq, p *actions.DataPermission) error {
    var err error
    var data models.HtTalent
    var pt models.HtProjectTalent
    err = e.Orm.Table(pt.TableName()).Where("talent_id in ?", d.Ids).Delete(&pt).Error
    // 同时删除关联表
    if err != nil {
        e.Log.Errorf("Service 删除项目人员关联表 error:%s \r\n", err)
        return err
    }
    db := e.Orm.Model(&data).
        Scopes(
            actions.Permission(data.TableName(), p),
        ).Delete(&data, d.GetId())
    // 同时删除关联表
    if err = db.Error; err != nil {
        e.Log.Errorf("Service RemoveHtTalent error:%s \r\n", err)
        return err
    }
    if db.RowsAffected == 0 {
        return errors.New("无权删除该数据")
    }
    return nil
}

// RemoveResume 删除HtTalent
func (e *HtTalent) RemoveResume(d *dto.HtTalentResumeDeleteReq, p *actions.DataPermission) error {
    var err error
    var pt models.HtResume
    db := e.Orm.Scopes(
        actions.Permission(pt.TableName(), p),
    ).Unscoped().Where("talent_id = ? and file_uri = ?", d.TalentId, d.FileUri).Delete(&pt)
    if err = db.Error; err != nil {
        e.Log.Errorf("Service RemoveResume error:%s \r\n", err)
        return err
    }
    if db.RowsAffected == 0 {
        return errors.New("无权删除该数据")
    }
    return nil
}
